package com.wy.panda.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSONObject;
import com.wy.panda.common.model.R;
import com.wy.panda.common.util.CollectionUtils;

/**
 * 系统统一错误处理
 * @author wangyuan
 * @since 2019年11月2日 上午1:49:50
 *
 */
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class SlothErrorController implements ErrorController {
	
	@Autowired
	private ErrorAttributes errorAttributes;
	
	@RequestMapping
	public R<?> errorHandler (HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request, true);
		
		JSONObject data = new JSONObject();
		HttpStatus status = getStatus(request);
		data.put("status", status.value());
		if(CollectionUtils.isNotEmpty(body)) {
			if(body.get("message") != null) {
				data.put("message", body.get("message"));
			}
			if(body.get("error") != null) {
				data.put("error", body.get("error"));
			}
			if(body.get("timestamp") != null) {
				data.put("timestamp", body.get("timestamp"));
			}
		}
		return R.error(R.ERROR_CODE, data);
	}

	@Override
	public String getErrorPath() {
		return null;
	}
	
	protected Map<String, Object> getErrorAttributes(HttpServletRequest request,
			boolean includeStackTrace) {
		WebRequest webRequest = new ServletWebRequest(request);
		return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
	}
	
	protected HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request
				.getAttribute("javax.servlet.error.status_code");
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		
		try {
			return HttpStatus.valueOf(statusCode);
		} catch (Exception ex) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
	}

}
